import 'package:get/get.dart';
import '../model/ai_chat_message_model.dart';

/// AI聊天状态管理
class AiChatState extends GetxController {
  // 所有消息
  final RxList<AiChatMessageModel> _allMessages = <AiChatMessageModel>[].obs;

  // 当前会话ID
  final RxString _currentConversationId = ''.obs;

  // 当前会话ID
  final RxString _currentSessionId = ''.obs;

  // 是否正在发送消息
  final RxBool _isSending = false.obs;

  /// 获取所有消息
  List<AiChatMessageModel> get allMessages => _allMessages.toList();

  /// 获取当前会话ID
  String get currentConversationId => _currentConversationId.value;

  /// 获取当前会话ID
  String get currentSessionId => _currentSessionId.value;

  /// 是否正在发送消息
  bool get isSending => _isSending.value;

  /// 设置会话ID
  void setConversationId(String conversationId) {
    _currentConversationId.value = conversationId;
  }

  /// 设置会话ID
  void setSessionId(String sessionId) {
    _currentSessionId.value = sessionId;
  }

  /// 添加消息
  void addMessage(AiChatMessageModel message) {
    if (message.isValid) {
      _allMessages.add(message);
      // 按时间排序
      _allMessages.sort((a, b) => a.timestamp.compareTo(b.timestamp));
    }
  }

  /// 添加用户消息
  void addUserMessage(String content) {
    final message = AiChatMessageModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      messageType: AiMessageType.user,
      content: content,
      timestamp: DateTime.now(),
      isSending: false,
    );
    addMessage(message);
  }

  /// 添加AI消息
  void addAiMessage(String content, {String? conversationId, int? showSec}) {
    final message = AiChatMessageModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      messageType: AiMessageType.ai,
      content: content,
      timestamp: DateTime.now(),
      conversationId: conversationId,
      showSec: showSec,
    );
    addMessage(message);
  }

  /// 更新消息状态
  void updateMessageStatus(
    String messageId, {
    bool? isSending,
    bool? isFailed,
  }) {
    final index = _allMessages.indexWhere((msg) => msg.id == messageId);
    if (index != -1) {
      final message = _allMessages[index];
      _allMessages[index] = message.copyWith(
        isSending: isSending ?? message.isSending,
        isFailed: isFailed ?? message.isFailed,
      );
    }
  }

  /// 更新消息内容
  void updateMessageContent(String messageId, String content) {
    final index = _allMessages.indexWhere((msg) => msg.id == messageId);
    if (index != -1) {
      final message = _allMessages[index];
      _allMessages[index] = message.copyWith(content: content);
    }
  }

  /// 移除消息
  void removeMessage(String messageId) {
    _allMessages.removeWhere((msg) => msg.id == messageId);
  }

  /// 设置发送状态
  void setSending(bool sending) {
    _isSending.value = sending;
  }

  /// 清空所有消息
  void clearAllMessages() {
    _allMessages.clear();
  }

  /// 清空会话
  void clearSession() {
    _allMessages.clear();
    _currentConversationId.value = '';
    _currentSessionId.value = '';
  }

  /// 获取最后一条消息
  AiChatMessageModel? getLastMessage() {
    if (_allMessages.isEmpty) return null;
    return _allMessages.last;
  }

  /// 获取用户消息数量
  int getUserMessageCount() {
    return _allMessages
        .where((msg) => msg.messageType == AiMessageType.user)
        .length;
  }

  /// 获取AI消息数量
  int getAiMessageCount() {
    return _allMessages
        .where((msg) => msg.messageType == AiMessageType.ai)
        .length;
  }

  /// 生成会话ID
  String generateSessionId() {
    final now = DateTime.now();
    final timestamp =
        '${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}';
    final random = (DateTime.now().millisecondsSinceEpoch % 10000000000000000)
        .toString()
        .padLeft(16, '0');
    return '${timestamp}_$random';
  }

  @override
  void onInit() {
    super.onInit();
    // 初始化会话ID
    _currentSessionId.value = generateSessionId();
  }
}
